// 用于对话
let webSocket;
// 用于上传文件
let uploadWebSocket;

class Talk {
    constructor() {
        if ("WebSocket" in window) {
            console.info("浏览器支持WebSocket");
        } else {
            // 浏览器不支持 WebSocket
            console.error("浏览器不支持WebSocket!");
        }
    }

    /**
     * 打开websocket的连接
     */
    openWebSocket() {
        let username = $('#username').val();
        if ("" == username || null == username || undefined == username) {
            console.warn('参数username不能为空');
            return;
        }

        // webSocket = new WebSocket(`ws://192.168.80.109:12101/im-end-web/ws/v1/${username}`, 'Authorization\'4f52f26643d647b9b6a4e94c1147f9c2');
//        webSocket = new WebSocket(`ws://localhost:17101/im-end-web/ws/v1/${username}`, 'Authorization\'4f52f26643d647b9b6a4e94c1147f9c2');
        webSocket = new WebSocket(`ws://localhost:15101/im-end-web-cluster/ws/v1/${username}`, 'Authorization\'4f52f26643d647b9b6a4e94c1147f9c2');
        let that = this;

        /**
         * 连通之后的回调事件
         */
        webSocket.onopen = function () {
            let username = $('#username').val();
            console.log(`${username}已经上线了`);
        };

        /**
         * 接收后台服务端的消息
         * @param {*} evt 
         */
        webSocket.onmessage = function (evt) {
            let messageString = evt.data;
            console.log(`数据已接收:${messageString}`);

            let messageObject = JSON.parse(messageString);
            that.setMessageInnerHTML("【" + messageObject.fromUserAccount + "】对【" + messageObject.toUserAccount + "】说：" + messageObject.content);
        };

        /**
         * 连接发生错误的回调方法
         */
        webSocket.onerror = function (e) {
            console.error("WebSocket连接发生错误");
        };

        /**
         * 连接关闭的回调事件
         */
        webSocket.onclose = function () {
            console.log("连接已关闭...");
            that.setMessageInnerHTML("连接已经关闭....");
        };
    }

    /**
     * 向服务端发送消息
     */
    sendMessage() {
        let fromUserAccount = $("#username").val();
        let toUserAccount = $("#toUsername").val();
        let content = $("#textarea").val();

        let messageString = "【" + fromUserAccount + "】对【" + toUserAccount + "】说：" + content;
        console.info(messageString);

        this.setMessageInnerHTML(messageString);
        let messageObject = new Message(content, fromUserAccount, toUserAccount, 1);
        webSocket.send(JSON.stringify(messageObject));
        $("#textarea").val("");
    }

    /**
     * 直接关闭websocket的连接
     */
    closeWebSocket() {
        webSocket.close();
    }

    /**
     * 将消息显示在网页上
     * @param {*} innerHTML 
     */
    setMessageInnerHTML(innerHTML) {
        $('#chat').append(innerHTML + '<br/>');
    }

    /**
     * 上传文件
     * @returns 
     */
    upload() {
        let username = $('#username').val();
        if ("" == username || null == username || undefined == username) {
            console.warn('参数username不能为空');
            return;
        }
        let toUsername = $('#toUsername').val();
        if ("" == toUsername || null == toUsername || undefined == toUsername) {
            console.warn('参数toUsername不能为空');
            return;
        }

        let filenameArray = $('#file').val().split('\\');
        let filename = filenameArray[filenameArray.length - 1];

        let type = 2;

        uploadWebSocket = new WebSocket(`ws://localhost:17101/im-end-web/ws/v1/upload/${username}/${toUsername}/${filename}/${type}`, 'Authorization\'4f52f26643d647b9b6a4e94c1147f9c2');
        // uploadWebSocket = new WebSocket(`ws://192.168.80.109:12101/im-end-web/ws/v1/upload/${username}/${toUsername}/${filename}/${type}`, 'Authorization\'4f52f26643d647b9b6a4e94c1147f9c2');

        /**
         * 连通之后的回调事件
         */
        uploadWebSocket.onopen = function () {
            let username = $('#username').val();
            console.log(`${username}已经上线了`);

            function uploadFile() {
                return new Promise(function (resolve, reject) {
                    let target = document.getElementById("file");
                    let reader = new FileReader();
                    reader.readAsArrayBuffer(target.files[0])
                    reader.onload = function () {
                        resolve(this.result);
                    };
                })
            };

            uploadFile().then(function (result) {
                uploadWebSocket.send(result);
            });
        };

        /**
         * 接收到消息的回调方法
         */
        uploadWebSocket.onmessage = function (event) {
            var messageJson = eval("(" + event.data + ")");
            console.info(`收到的来自服务端的消息是【${JSON.stringify(messageJson)}】`);
        };

        /**
         * 连接发生错误的回调方法
         */
        uploadWebSocket.onerror = function (e) {
            console.error("WebSocket连接发生错误", e);
        };

        /**
         * 连接关闭的回调方法
         */
        uploadWebSocket.onclose = function () {
            console.error("WebSocket连接关闭");
        }
    }
}

let talk = new Talk();

$(document).ready(function () {
    $("#openConnection").click(function () {
        talk.openWebSocket();
    });

    $("#closeConnection").click(function () {
        talk.closeWebSocket();
    });

    $("#sendMessage").click(function () {
        talk.sendMessage();
    });

    $("#upload").click(function () {
        talk.upload();
    });
});

